<template>
  <a-modal
    :title="title"
    :width="350"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :footer="null"
    @cancel="handleCancel"
    style="top:15%;height: 60%;">
    <a-spin :spinning="confirmLoading">
      <div class="main">
        <a-form :form="form" class="user-layout-login" ref="formLogin" id="formLogin">
          <a-form-item>
            <a-input
              size="large"
              v-decorator="['loginName',{initialValue:'', rules: validatorRules.loginName.rules}]"
              type="text"
              placeholder="请输入用户名">
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-input
              v-decorator="['password',{initialValue:'', rules: validatorRules.password.rules}]"
              size="large"
              type="password"
              autocomplete="false"
              placeholder="请输入密码">
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
          <a-row :gutter="0">
            <a-col :span="14">
              <a-form-item>
                <a-input
                  v-decorator="['inputCode']"
                  size="large"
                  type="text"
                  default-value=""
                  placeholder="请输入验证码">
                  <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="10" style="text-align: right">
              <img v-if="requestCodeSuccess" style="margin-top: 2px;" :src="randCodeImage" @click="handleChangeCheckCode"/>
              <img v-else style="margin-top: 2px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode"/>
            </a-col>
          </a-row>
          <a-form-item>
            <a-checkbox :checked="checked" @change="handleChange">记住密码</a-checkbox>
          </a-form-item>
          <a-form-item style="margin-top:16px">
            <a-button
              size="large"
              type="primary"
              htmlType="submit"
              class="login-button"
              :loading="loginBtn"
              @click.stop.prevent="handleSubmit"
              :disabled="loginBtn">登 录
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import md5 from 'md5'
import Vue from 'vue'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { getAction } from '@/api/manage'
import { login } from '@api/login'
import { ACCESS_TOKEN, USER_ID, USER_INFO, USER_LOGIN_NAME } from '@/store/mutation-types'
export default {
  name: "LoginModal",
  data () {
    return {
      title:"登录",
      visible: false,
      model: {},
      loginType: 0,
      loginBtn: false,
      checked: false,
      confirmLoading: false,
      randCodeImage:'',
      requestCodeSuccess:false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      form: this.$form.createForm(this),
      validatorRules:{
        loginName:{rules: [{ required: true, message: '请输入用户名!'},{validator: this.handleLoginName}]},
        password:{rules: [{ required: true, message: '请输入密码!',validator: 'click'}]}
      },
    }
  },
  created () {
    this.handleChangeCheckCode()
  },
  methods: {
    show() {
      this.visible = true
      //从缓存中获取登录名和密码
      this.$nextTick(() => {
        if(Vue.ls.get('cache_loginName') && Vue.ls.get('cache_password')) {
          this.form.setFieldsValue({'loginName': Vue.ls.get('cache_loginName')})
          this.form.setFieldsValue({'password': Vue.ls.get('cache_password')})
          this.checked = true
        }
      })
    },
    handleChangeCheckCode(){
      getAction('/user/randomImage').then(res=>{
        if(res.code === 200){
          this.uuid = res.data.uuid
          this.randCodeImage = res.data.base64
          this.requestCodeSuccess=true
        }else{
          this.$message.error(res.data)
          this.requestCodeSuccess=false
        }
      }).catch(()=>{
        this.requestCodeSuccess=false
      })
    },
    handleLoginName (rule, value, callback) {
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      if (regex.test(value)) {
        this.loginType = 0
      } else {
        this.loginType = 1
      }
      callback()
    },
    handleChange(e) {
      this.checked = e.target.checked
    },
    handleSubmit () {
      let that = this
      let loginParams = {};
      that.loginBtn = true;
      // 使用账户密码登陆
      that.form.validateFields([ 'loginName', 'password', 'inputCode' ], { force: true }, (err, values) => {
        if (!err) {
          loginParams.loginName = values.loginName
          loginParams.password = md5(values.password)
          loginParams.code = values.inputCode
          loginParams.uuid = that.uuid
          if(that.checked) {
            //勾选的时候进行缓存
            Vue.ls.set('cache_loginName', values.loginName)
            Vue.ls.set('cache_password', values.password)
          } else {
            //没勾选的时候清缓存
            Vue.ls.remove('cache_loginName')
            Vue.ls.remove('cache_password')
          }
          login(loginParams).then(response => {
            if(response.code === 200){
              let err = {};
              if(response.data.msgTip === 'user can login'){
                const result = response.data
                Vue.ls.set(USER_ID, result.user.id, 7 * 24 * 60 * 60 * 1000);
                Vue.ls.set(USER_LOGIN_NAME, result.user.loginName, 7 * 24 * 60 * 60 * 1000);
                //前端7天有效期，后端默认1天，只要用户在1天内有访问页面就可以一直续期直到7天结束
                Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
                Vue.ls.set(USER_INFO, result.user, 7 * 24 * 60 * 60 * 1000)
                this.loginSuccess(response)
                that.visible = false
                that.$emit("ok", result.user)
              } else if(response.data.msgTip === 'user is not exist'){
                err.message = '用户不存在';
                this.requestFailed(err)
              } else if(response.data.msgTip === 'user password error'){
                err.message = '用户密码不正确';
                this.requestFailed(err)
              } else if(response.data.msgTip === 'user is black'){
                err.message = '用户被禁用';
                this.requestFailed(err)
              } else if(response.data.msgTip === 'tenant is black'){
                if(loginParams.loginName === 'jsh') {
                  err.message = 'jsh用户已停用，请注册租户进行体验！';
                } else {
                  err.message = '用户所属的租户被禁用';
                }
                this.requestFailed(err)
              } else if(response.data.msgTip === 'tenant is expire'){
                err.message = '试用期已结束，请联系客服续费';
                this.requestFailed(err)
              } else if(response.data.msgTip === 'access service error'){
                err.message = '查询服务异常';
                this.requestFailed(err)
              }
            } else{
              this.requestFailed(response)
            }
          }).catch(error => {
            that.requestFailed(error);
          })
        } else {
          that.loginBtn = false;
        }
      })
    },
    loginSuccess (res) {
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`,
      });
      if(res.data && res.data.user) {
        if(res.data.user.loginName === 'admin'){
          let desc = 'admin只是平台运维用户，真正的管理员是租户(测试账号为jsh），admin不能编辑任何业务数据，只能配置平台菜单和创建租户'
          this.$message.info(desc,30)
        } else {
          getAction("/user/infoWithTenant",{}).then(res=>{
            if(res && res.code === 200) {
            }
          })
        }
      }
    },
    requestFailed (err) {
      this.$notification[ 'error' ]({
        message: '登录失败',
        description: ((err.response || {}).data || {}).message || err.message || err.data.message || "请求出现错误，请稍后再试",
        duration: 4,
      });
      //验证码刷新
      this.form.setFieldsValue({'inputCode':''})
      this.handleChangeCheckCode()
      this.loginBtn = false;
    },
    close () {
      this.$emit('close');
      this.visible = false;
    },
    handleCancel () {
      this.close()
    },
  }
}
</script>

<style scoped>
  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }
</style>